/**
 * 扫描 input
 */

import {connect, mapProps, mapReadPretty} from '@formily/react';
import {Input, message} from 'antd';
import { useState, useRef } from "react";
import {getBills} from "@/biz-components/package-input/service";
import { useFormEffects } from "@formily/react";
import { onFormMount } from '@formily/core';

interface PackageInputProps {
    pCompany: string,
    pDepartment: string,
    codeParams?: string,
    noCompany?: boolean,
    url?: string,
}

const { Search } = Input;

export const PackageInput = (props: PackageInputProps) => {
    const { pCompany, pDepartment, onChange, codeParams = 'billCode', noCompany = false, url } = props;
    const [loading, setloading] = useState<boolean>(false);
    const curForm = useRef<any>();
    const [value, setValue] = useState();
    useFormEffects(() => {
        onFormMount((form) => {
            curForm.current = form;
        });
    });
    const handleSearch = (value: string) => {

        const params = {
            [codeParams]: value,
        };
        if (!noCompany) {
            if (!curForm?.current?.getValuesIn('pCompany')) {
                return message.error('清选择打包人所属公司');
            } else {
                params.pCompany = curForm?.current?.getValuesIn('pCompany');
            }
        }
        if(value?.length >= 12) {
            setloading(true);
            getBills(url, params).then(({ success, result }) => {
                setloading(false);
                if (!success) {
                    return;
                }
                if (!result) {
                    return;
                }
                onChange(result);
            }).finally(() => {
                setloading(false);
                setValue('')
            });
        }
    };
    const onChangeHandle = (e:any) => {
        setValue(e?.target?.value)
    }
    return <>
        <Search
            placeholder="请输入打包单编码或扫描条码"
            enterButton="添加"
            allowClear
            value={value}
            loading={loading}
            onSearch={handleSearch}
            onChange={onChangeHandle}
        />
    </>;
};

export default connect(
    PackageInput,
    mapProps((props: any, field) => {
        const error = !!(Array.isArray(field?.errors) && field?.errors?.length);
        return {
            ...props,
            error
        };
    }),
    mapReadPretty(props => <PackageInput {...props} disabled />)
);
